<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wrr123.github.io","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="mybatis 不要为了多个查询条件而写 1&#x3D;1 当遇到多个查询条件，使用where 1&#x3D;1 可以很方便的解决我们的问题，但是这样很可能会造成非常大的性能损失，因为添加了 “where 1&#x3D;1 ”的过滤条件之后，数据库系统就无法使用索引等查询优化策略，数据库系统将会被迫对每行数据进行扫描（即全表扫描） 以比较此行是否满足过滤条件，当表中的数据量较大时查询速度会非常慢；此外，还会存在SQL 注入的风">
<meta property="og:type" content="article">
<meta property="og:title" content="java代码规范">
<meta property="og:url" content="https://wrr123.github.io/2020/09/27/java%E4%BB%A3%E7%A0%81%E8%A7%84%E8%8C%83/index.html">
<meta property="og:site_name" content="一缕烟气">
<meta property="og:description" content="mybatis 不要为了多个查询条件而写 1&#x3D;1 当遇到多个查询条件，使用where 1&#x3D;1 可以很方便的解决我们的问题，但是这样很可能会造成非常大的性能损失，因为添加了 “where 1&#x3D;1 ”的过滤条件之后，数据库系统就无法使用索引等查询优化策略，数据库系统将会被迫对每行数据进行扫描（即全表扫描） 以比较此行是否满足过滤条件，当表中的数据量较大时查询速度会非常慢；此外，还会存在SQL 注入的风">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-09-27T05:40:22.000Z">
<meta property="article:modified_time" content="2022-02-18T02:52:04.442Z">
<meta property="article:author" content="田园隐士">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://wrr123.github.io/2020/09/27/java%E4%BB%A3%E7%A0%81%E8%A7%84%E8%8C%83/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>java代码规范 | 一缕烟气</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一缕烟气" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">一缕烟气</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">沧海月明珠有泪，蓝田日暖玉生烟</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wrr123.github.io/2020/09/27/java%E4%BB%A3%E7%A0%81%E8%A7%84%E8%8C%83/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="田园隐士">
      <meta itemprop="description" content="talk is cheap, show me the code">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一缕烟气">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          java代码规范
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-09-27 13:40:22" itemprop="dateCreated datePublished" datetime="2020-09-27T13:40:22+08:00">2020-09-27</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2022-02-18 10:52:04" itemprop="dateModified" datetime="2022-02-18T10:52:04+08:00">2022-02-18</time>
              </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>9.7k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>9 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h4 id="mybatis-不要为了多个查询条件而写-1-1"><a href="#mybatis-不要为了多个查询条件而写-1-1" class="headerlink" title="mybatis 不要为了多个查询条件而写 1=1"></a>mybatis 不要为了多个查询条件而写 <code>1=1</code></h4><blockquote>
<p>当遇到多个查询条件，使用where 1=1 可以很方便的解决我们的问题，但是这样很可能会造成非常大的性能损失，因为添加了 “where 1=1 ”的过滤条件之后，数据库系统就无法使用索引等查询优化策略，数据库系统将会被迫对每行数据进行扫描（即全表扫描） 以比较此行是否满足过滤条件，当表中的数据量较大时查询速度会非常慢；此外，还会存在SQL 注入的风险。</p>
</blockquote>
<p>一个反例：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;queryBookInfo&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;com.tjt.platform.entity.BookInfo&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;java.lang.Integer&quot;</span>&gt;</span>  </span><br><span class="line"> select count(*) from t_rule_BookInfo t where 11=1  </span><br><span class="line"><span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;title !=null and title !=&#x27;&#x27; &quot;</span>&gt;</span>  </span><br><span class="line"> AND title = #&#123;title&#125;   </span><br><span class="line"><span class="tag">&lt;/<span class="name">if</span>&gt;</span>   </span><br><span class="line"><span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;author !=null and author !=&#x27;&#x27; &quot;</span>&gt;</span>  </span><br><span class="line"> AND author = #&#123;author&#125;  </span><br><span class="line"><span class="tag">&lt;/<span class="name">if</span>&gt;</span>   </span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span> </span><br></pre></td></tr></table></figure>
<p>一个正例：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;queryBookInfo&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;com.tjt.platform.entity.BookInfo&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;java.lang.Integer&quot;</span>&gt;</span>  </span><br><span class="line"> select count(*) from t_rule_BookInfo t  </span><br><span class="line"><span class="tag">&lt;<span class="name">where</span>&gt;</span>  </span><br><span class="line"><span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;title !=null and title !=&#x27;&#x27; &quot;</span>&gt;</span>  </span><br><span class="line"> title = #&#123;title&#125;   </span><br><span class="line"><span class="tag">&lt;/<span class="name">if</span>&gt;</span>  </span><br><span class="line"><span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;author !=null and author !=&#x27;&#x27; &quot;</span>&gt;</span>   </span><br><span class="line"> AND author = #&#123;author&#125;  </span><br><span class="line"><span class="tag">&lt;/<span class="name">if</span>&gt;</span>  </span><br><span class="line"><span class="tag">&lt;/<span class="name">where</span>&gt;</span>   </span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span> </span><br></pre></td></tr></table></figure>
<p><strong>UPDATE 操作也一样，可以用标记 <code>where</code> 来代替 <code>1=1</code></strong></p>
<span id="more"></span>
<h4 id="迭代-entrySet-获取-Map-的-key-和-value"><a href="#迭代-entrySet-获取-Map-的-key-和-value" class="headerlink" title="迭代 entrySet() 获取 Map 的 key 和 value"></a>迭代 <code>entrySet()</code> 获取 Map 的 key 和 value</h4><p>当循环中只需要获取 Map 的主键 key 时，迭代 ketSet() 是正确的；但是，当需要主键 key 和取值 value 时，迭代 entrySet() 才是最高效的做法，其比迭代 keySet() 后再去通过 get 取值性能更佳。</p>
<p>一个反例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Map 获取value 反例:  </span></span><br><span class="line">HashMap&lt;String, String&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();  </span><br><span class="line"><span class="keyword">for</span> (String key : map.keySet())&#123;  </span><br><span class="line">    <span class="type">String</span> <span class="variable">value</span> <span class="operator">=</span> map.get(key);  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<p>一个正例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Map 获取key &amp; value 正例:  </span></span><br><span class="line">HashMap&lt;String, String&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();  </span><br><span class="line"><span class="keyword">for</span> (Map.Entry&lt;String,String&gt; entry : map.entrySet())&#123;  </span><br><span class="line"> <span class="type">String</span> <span class="variable">key</span> <span class="operator">=</span> entry.getKey();  </span><br><span class="line"> <span class="type">String</span> <span class="variable">value</span> <span class="operator">=</span> entry.getValue();  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<h4 id="使用-Collection-isEmpty-检测空"><a href="#使用-Collection-isEmpty-检测空" class="headerlink" title="使用 Collection.isEmpty() 检测空"></a>使用 Collection.isEmpty() 检测空</h4><blockquote>
<p>使用Collection.size() 来检测是否为空在逻辑上没有问题，但是使用Collection.isEmpty() 使得代码更易读，并且可以获得更好的性能；除此之外，任何Collection.isEmpty() 实现的时间复杂度都是O(1) ，不需要多次循环遍历，但是某些通过Collection.size() 方法实现的时间复杂度可能是O(n)</p>
</blockquote>
<p>一个反例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">LinkedList&lt;Object&gt; collection = <span class="keyword">new</span> <span class="title class_">LinkedList</span>&lt;&gt;();  </span><br><span class="line"><span class="keyword">if</span> (collection.size() == <span class="number">0</span>)&#123;  </span><br><span class="line"> System.out.println(<span class="string">&quot;collection is empty.&quot;</span>);  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<p>一个正例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">LinkedList&lt;Object&gt; collection = <span class="keyword">new</span> <span class="title class_">LinkedList</span>&lt;&gt;();  </span><br><span class="line"><span class="keyword">if</span> (collection.isEmpty())&#123;  </span><br><span class="line">    System.out.println(<span class="string">&quot;collection is empty.&quot;</span>);  </span><br><span class="line">&#125;  </span><br><span class="line"><span class="comment">//检测是否为null 可以使用CollectionUtils.isEmpty()  </span></span><br><span class="line"><span class="keyword">if</span> (CollectionUtils.isEmpty(collection))&#123; </span><br><span class="line">     System.out.println(<span class="string">&quot;collection is null.&quot;</span>);  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<h4 id="初始化集合时，尽量指定其大小"><a href="#初始化集合时，尽量指定其大小" class="headerlink" title="初始化集合时，尽量指定其大小"></a>初始化集合时，尽量指定其大小</h4><p>尽量在初始化时，指定集合的大小，能有效减少集合的扩容次数，因为集合每次扩容的时间复杂度很可能是 <code>O(n)</code>,耗费时间和性能。</p>
<p>一个反例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//初始化list，往list 中添加元素反例： </span></span><br><span class="line"> </span><br><span class="line"><span class="type">int</span>[] arr = <span class="keyword">new</span> <span class="title class_">int</span>[]&#123;<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>&#125;;  </span><br><span class="line">List&lt;Integer&gt; list = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();  </span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> i : arr)&#123;  </span><br><span class="line"> list.add(i);  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<p>一个正例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//初始化list，往list 中添加元素正例：  </span></span><br><span class="line"><span class="type">int</span>[] arr = <span class="keyword">new</span> <span class="title class_">int</span>[]&#123;<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>&#125;;  </span><br><span class="line"><span class="comment">//指定集合list 的容量大小  </span></span><br><span class="line">List&lt;Integer&gt; list = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;(arr.length);  </span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> i : arr)&#123;  </span><br><span class="line">    list.add(i);  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<h5 id="使用-StringBuilder-拼接字符串"><a href="#使用-StringBuilder-拼接字符串" class="headerlink" title="使用 StringBuilder 拼接字符串"></a>使用 StringBuilder 拼接字符串</h5><p>一般的字符串拼接在编译期 Java 会对其进行优化，但是在循环中字符串的拼接 Java 编译期无法执行优化，所以需要使用 StringBuilder 进行替换</p>
<p>一个反例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//在循环中拼接字符串反例  </span></span><br><span class="line"><span class="type">String</span> <span class="variable">str</span> <span class="operator">=</span> <span class="string">&quot;&quot;</span>;  </span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">10</span>; i++)&#123;  </span><br><span class="line">    <span class="comment">//在循环中字符串拼接Java 不会对其进行优化  </span></span><br><span class="line">    str += i;  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<p>一个正例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//在循环中拼接字符串正例  </span></span><br><span class="line"><span class="type">String</span> <span class="variable">str1</span> <span class="operator">=</span> <span class="string">&quot;Love&quot;</span>;  </span><br><span class="line"><span class="type">String</span> <span class="variable">str2</span> <span class="operator">=</span> <span class="string">&quot;Courage&quot;</span>;  </span><br><span class="line"><span class="type">String</span> <span class="variable">strConcat</span> <span class="operator">=</span> str1 + str2;  <span class="comment">//Java 编译器会对该普通模式的字符串拼接进行优化  </span></span><br><span class="line"><span class="type">StringBuilder</span> <span class="variable">sb</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">StringBuilder</span>();  </span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">10</span>; i++)&#123;  </span><br><span class="line">   <span class="comment">//在循环中，Java 编译器无法进行优化，所以要手动使用StringBuilder  </span></span><br><span class="line">   &amp;nbsp;sb.append(i);  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<h4 id="若需频繁调用-Collection-contains-方法则使用-Set"><a href="#若需频繁调用-Collection-contains-方法则使用-Set" class="headerlink" title="若需频繁调用 Collection.contains() 方法则使用 Set"></a>若需频繁调用 Collection.contains() 方法则使用 Set</h4><blockquote>
<p>在Java 集合类库中，List的contains 方法普遍时间复杂度为O(n)，若代码中需要频繁调用contains 方法查找数据则先将集合list 转换成HashSet 实现，将O(n) 的时间复杂度将为O(1)。</p>
</blockquote>
<p>一个反例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//频繁调用Collection.contains() 反例  </span></span><br><span class="line">List&lt;Object&gt; list = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();  </span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt;= Integer.MAX_VALUE; i++)&#123;  </span><br><span class="line">    <span class="comment">//时间复杂度为O(n)  </span></span><br><span class="line">    <span class="keyword">if</span> (list.contains(i))  </span><br><span class="line">    System.out.println(<span class="string">&quot;list contains &quot;</span>+ i);  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>一个正例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//频繁调用Collection.contains() 正例  </span></span><br><span class="line">List&lt;Object&gt; list = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();  </span><br><span class="line">Set&lt;Object&gt; set = <span class="keyword">new</span> <span class="title class_">HashSet</span>&lt;&gt;();  </span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt;= Integer.MAX_VALUE; i++)&#123;  </span><br><span class="line">    <span class="comment">//时间复杂度为O(1)  </span></span><br><span class="line">    <span class="keyword">if</span> (set.contains(i))&#123;  </span><br><span class="line">        System.out.println(<span class="string">&quot;list contains &quot;</span>+ i);  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<h4 id="使用静态代码块实现赋值静态成员变量"><a href="#使用静态代码块实现赋值静态成员变量" class="headerlink" title="使用静态代码块实现赋值静态成员变量"></a>使用静态代码块实现赋值静态成员变量</h4><p>对于集合类型的静态成员变量，应该使用静态代码块赋值，而不是使用集合实现来赋值。</p>
<p>一个反例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//赋值静态成员变量反例 </span></span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> Map&lt;String, Integer&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;String, Integer&gt;()&#123;  </span><br><span class="line">    &#123;  </span><br><span class="line">        map.put(<span class="string">&quot;Leo&quot;</span>,<span class="number">1</span>);  </span><br><span class="line">        map.put(<span class="string">&quot;Family-loving&quot;</span>,<span class="number">2</span>);  </span><br><span class="line">        map.put(<span class="string">&quot;Cold on the out side passionate on the inside&quot;</span>,<span class="number">3</span>);  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;; </span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> List&lt;String&gt; list = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;()&#123;  </span><br><span class="line">    &#123;  </span><br><span class="line">        list.add(<span class="string">&quot;Sagittarius&quot;</span>);  </span><br><span class="line">        list.add(<span class="string">&quot;Charming&quot;</span>);  </span><br><span class="line">        list.add(<span class="string">&quot;Perfectionist&quot;</span>);  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;; </span><br></pre></td></tr></table></figure>
<p>一个正例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//赋值静态成员变量正例  </span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> Map&lt;String, Integer&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;String, Integer&gt;();  </span><br><span class="line"><span class="keyword">static</span> &#123;  </span><br><span class="line">    map.put(<span class="string">&quot;Leo&quot;</span>,<span class="number">1</span>);  </span><br><span class="line">    map.put(<span class="string">&quot;Family-loving&quot;</span>,<span class="number">2</span>);  </span><br><span class="line">    map.put(<span class="string">&quot;Cold on the out side passionate on the inside&quot;</span>,<span class="number">3</span>);  </span><br><span class="line">&#125;  </span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> List&lt;String&gt; list = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;(); </span><br><span class="line"> <span class="keyword">static</span> &#123;  </span><br><span class="line">    list.add(<span class="string">&quot;Sagittarius&quot;</span>);  </span><br><span class="line">    list.add(<span class="string">&quot;Charming&quot;</span>);  </span><br><span class="line">    list.add(<span class="string">&quot;Perfectionist&quot;</span>);  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<h4 id="删除未使用的局部变量、方法参数、私有方法、字段和多余的括号。"><a href="#删除未使用的局部变量、方法参数、私有方法、字段和多余的括号。" class="headerlink" title="删除未使用的局部变量、方法参数、私有方法、字段和多余的括号。"></a>删除未使用的局部变量、方法参数、私有方法、字段和多余的括号。</h4><h4 id="工具类中屏蔽构造函数"><a href="#工具类中屏蔽构造函数" class="headerlink" title="工具类中屏蔽构造函数"></a>工具类中屏蔽构造函数</h4><blockquote>
<p>工具类是一堆静态字段和函数的集合，其不应该被实例化；但是，Java 为每个没有明确定义构造函数的类添加了一个隐式公有构造函数，为了避免不必要的实例化，应该显式定义私有构造函数来屏蔽这个隐式公有构造函数。</p>
</blockquote>
<p>一个反例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">PasswordUtils</span> &#123;  </span><br><span class="line"><span class="comment">//工具类构造函数反例  </span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">Logger</span> <span class="variable">LOG</span> <span class="operator">=</span> LoggerFactory.getLogger(PasswordUtils.class);  </span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DEFAULT_CRYPT_ALGO</span> <span class="operator">=</span> <span class="string">&quot;PBEWithMD5AndDES&quot;</span>; </span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">encryptPassword</span><span class="params">(String aPassword)</span> <span class="keyword">throws</span> IOException &#123;  </span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">PasswordUtils</span>(aPassword).encrypt();  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>一个正例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">PasswordUtils</span> &#123;  </span><br><span class="line"><span class="comment">//工具类构造函数正例  </span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">Logger</span> <span class="variable">LOG</span> <span class="operator">=</span> LoggerFactory.getLogger(PasswordUtils.class);  </span><br><span class="line"><span class="comment">//定义私有构造函数来屏蔽这个隐式公有构造函数  </span></span><br><span class="line"><span class="keyword">private</span> <span class="title function_">PasswordUtils</span><span class="params">()</span>&#123;&#125; </span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DEFAULT_CRYPT_ALGO</span> <span class="operator">=</span> <span class="string">&quot;PBEWithMD5AndDES&quot;</span>;  </span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">encryptPassword</span><span class="params">(String aPassword)</span> <span class="keyword">throws</span> IOException &#123;  </span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">PasswordUtils</span>(aPassword).encrypt();  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="删除多余的异常捕获并抛出"><a href="#删除多余的异常捕获并抛出" class="headerlink" title="删除多余的异常捕获并抛出"></a>删除多余的异常捕获并抛出</h4><blockquote>
<p>用catch 语句捕获异常后，若什么也不进行处理，就只是让异常重新抛出，这跟不捕获异常的效果一样，可以删除这块代码或添加别的处理。</p>
</blockquote>
<p>一个反例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//多余异常反例  </span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> String <span class="title function_">fileReader</span><span class="params">(String fileName)</span><span class="keyword">throws</span> IOException&#123;  </span><br><span class="line">    <span class="keyword">try</span> (<span class="type">BufferedReader</span> <span class="variable">reader</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">BufferedReader</span>(<span class="keyword">new</span> <span class="title class_">FileReader</span>(fileName))) &#123;  </span><br><span class="line">        String line;  </span><br><span class="line">        <span class="type">StringBuilder</span> <span class="variable">builder</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">StringBuilder</span>();  </span><br><span class="line">        <span class="keyword">while</span> ((line = reader.readLine()) != <span class="literal">null</span>) &#123;  </span><br><span class="line">            builder.append(line);  </span><br><span class="line">        &#125;  </span><br><span class="line">        <span class="keyword">return</span> builder.toString();  </span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;  </span><br><span class="line">        <span class="comment">//仅仅是重复抛异常 未作任何处理  </span></span><br><span class="line">        <span class="keyword">throw</span> e;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<p>一个正例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//多余异常正例  </span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> String <span class="title function_">fileReader</span><span class="params">(String fileName)</span><span class="keyword">throws</span> IOException&#123;  </span><br><span class="line">    <span class="keyword">try</span> (<span class="type">BufferedReader</span> <span class="variable">reader</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">BufferedReader</span>(<span class="keyword">new</span> <span class="title class_">FileReader</span>(fileName))) &#123;  </span><br><span class="line">        String line;  </span><br><span class="line">        <span class="type">StringBuilder</span> <span class="variable">builder</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">StringBuilder</span>();  </span><br><span class="line">        <span class="keyword">while</span> ((line = reader.readLine()) != <span class="literal">null</span>) &#123;  </span><br><span class="line">            builder.append(line);  </span><br><span class="line">        &#125;  </span><br><span class="line">        <span class="keyword">return</span> builder.toString();  </span><br><span class="line">        <span class="comment">//删除多余的抛异常，或增加其他处理：  </span></span><br><span class="line">        <span class="comment">/*catch (Exception e) &#123;  </span></span><br><span class="line"><span class="comment">            return &quot;fileReader exception&quot;;  </span></span><br><span class="line"><span class="comment">        &#125;*/</span>  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="字符串转化使用-String-valueOf-value-代替-quot-quot-value"><a href="#字符串转化使用-String-valueOf-value-代替-quot-quot-value" class="headerlink" title="字符串转化使用 String.valueOf(value) 代替 &quot;&quot; + value"></a>字符串转化使用 String.valueOf(value) 代替 <code>&quot;&quot; + value</code></h4><blockquote>
<p>把其它对象或类型转化为字符串时，使用String.valueOf(value) 比 “”+value 的效率更高。</p>
</blockquote>
<p>一个反例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//把其它对象或类型转化为字符串反例：  </span></span><br><span class="line"><span class="type">int</span> <span class="variable">num</span> <span class="operator">=</span> <span class="number">520</span>;  </span><br><span class="line"><span class="comment">// &quot;&quot; + value  </span></span><br><span class="line"><span class="type">String</span> <span class="variable">strLove</span> <span class="operator">=</span> <span class="string">&quot;&quot;</span> + num; </span><br></pre></td></tr></table></figure>
<p>一个正例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//把其它对象或类型转化为字符串正例：  </span></span><br><span class="line"><span class="type">int</span> <span class="variable">num</span> <span class="operator">=</span> <span class="number">520</span>;  </span><br><span class="line"><span class="comment">// String.valueOf() 效率更高  </span></span><br><span class="line"><span class="type">String</span> <span class="variable">strLove</span> <span class="operator">=</span> String.valueOf(num); </span><br></pre></td></tr></table></figure>
<h4 id="避免使用-BigDecimal-double"><a href="#避免使用-BigDecimal-double" class="headerlink" title="避免使用 BigDecimal(double)"></a>避免使用 BigDecimal(double)</h4><blockquote>
<p>BigDecimal(double) 存在精度损失风险，在精确计算或值比较的场景中可能会导致业务逻辑异常。</p>
</blockquote>
<p>一个反例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// BigDecimal 反例      </span></span><br><span class="line"><span class="type">BigDecimal</span> <span class="variable">bigDecimal</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">BigDecimal</span>(<span class="number">0.11D</span>);</span><br></pre></td></tr></table></figure>
<p>一个正例:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// BigDecimal 正例  </span></span><br><span class="line"><span class="type">BigDecimal</span> <span class="variable">bigDecimalbigDecimal1</span> <span class="operator">=</span> bigDecimal.valueOf(<span class="number">0.11D</span>); </span><br></pre></td></tr></table></figure>
<h4 id="返回空数组和非-null"><a href="#返回空数组和非-null" class="headerlink" title="返回空数组和非 null"></a>返回空数组和非 null</h4><blockquote>
<p>若程序运行返回null，需要调用方强制检测null，否则就会抛出空指针异常；返回空数组或空集合，有效地避免了调用方因为未检测null 而抛出空指针异常的情况，还可以删除调用方检测null 的语句使代码更简洁。</p>
</blockquote>
<p>一个反例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//返回null 反例  </span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> Result[] getResults() &#123;  </span><br><span class="line">    <span class="keyword">return</span> <span class="literal">null</span>; </span><br><span class="line"> &#125;  </span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> List&lt;Result&gt; <span class="title function_">getResultList</span><span class="params">()</span> &#123;  </span><br><span class="line">    <span class="keyword">return</span> <span class="literal">null</span>;  </span><br><span class="line">&#125;  </span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> Map&lt;String, Result&gt; <span class="title function_">getResultMap</span><span class="params">()</span> &#123;  </span><br><span class="line">    <span class="keyword">return</span> <span class="literal">null</span>;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>一个正例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//返回空数组和空集正例  </span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> Result[] getResults() &#123;  </span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Result</span>[<span class="number">0</span>];  </span><br><span class="line">&#125;  </span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> List&lt;Result&gt; <span class="title function_">getResultList</span><span class="params">()</span> &#123;  </span><br><span class="line">    <span class="keyword">return</span> Collections.emptyList();  </span><br><span class="line">&#125;  </span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> Map&lt;String, Result&gt; <span class="title function_">getResultMap</span><span class="params">()</span> &#123;  </span><br><span class="line">    <span class="keyword">return</span> Collections.emptyMap();  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="优先使用常量或确定值调用-equals-方法"><a href="#优先使用常量或确定值调用-equals-方法" class="headerlink" title="优先使用常量或确定值调用 equals 方法"></a>优先使用常量或确定值调用 <code>equals</code> 方法</h4><blockquote>
<p>对象的equals 方法容易抛空指针异常，应使用常量或确定有值的对象来调用equals 方法。</p>
</blockquote>
<p>一个反例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//调用 equals 方法反例  </span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="type">boolean</span> <span class="title function_">fileReader</span><span class="params">(String fileName)</span><span class="keyword">throws</span> IOException&#123;  </span><br><span class="line"> <span class="comment">// 可能抛空指针异常 </span></span><br><span class="line">  <span class="keyword">return</span> fileName.equals(<span class="string">&quot;Charming&quot;</span>);  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>一个正例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//调用 equals 方法正例  </span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="type">boolean</span> <span class="title function_">fileReader</span><span class="params">(String fileName)</span><span class="keyword">throws</span> IOException&#123;  </span><br><span class="line">    <span class="comment">// 使用常量或确定有值的对象来调用 equals 方法  </span></span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;Charming&quot;</span>.equals(fileName);   </span><br><span class="line">    <span class="comment">//或使用：java.util.Objects.equals() 方法  </span></span><br><span class="line">   <span class="keyword">return</span> Objects.equals(<span class="string">&quot;Charming&quot;</span>,fileName);  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<h4 id="枚举的属性字段必须是私有且不可变"><a href="#枚举的属性字段必须是私有且不可变" class="headerlink" title="枚举的属性字段必须是私有且不可变"></a>枚举的属性字段必须是私有且不可变</h4><blockquote>
<p>枚举通常被当做常量使用，如果枚举中存在公共属性字段或设置字段方法，那么这些枚举常量的属性很容易被修改；理想情况下，枚举中的属性字段是私有的，并在私有构造函数中赋值，没有对应的Setter 方法，最好加上final 修饰符。</p>
</blockquote>
<p>一个反例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">enum</span> <span class="title class_">SwitchStatus</span> &#123;  </span><br><span class="line">    <span class="comment">// 枚举的属性字段反例  </span></span><br><span class="line">    DISABLED(<span class="number">0</span>, <span class="string">&quot;禁用&quot;</span>),  </span><br><span class="line">    ENABLED(<span class="number">1</span>, <span class="string">&quot;启用&quot;</span>);  </span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> value;  </span><br><span class="line">    <span class="keyword">private</span> String description;  </span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">SwitchStatus</span><span class="params">(<span class="type">int</span> value, String description)</span> &#123;  </span><br><span class="line">        <span class="built_in">this</span>.value = value;  </span><br><span class="line">        <span class="built_in">this</span>.description = description;  </span><br><span class="line">    &#125;  </span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getDescription</span><span class="params">()</span> &#123;  </span><br><span class="line">        <span class="keyword">return</span> description;  </span><br><span class="line">    &#125;  </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setDescription</span><span class="params">(String description)</span> &#123;  </span><br><span class="line">        <span class="built_in">this</span>.description = description;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<p>一个正例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">enum</span> <span class="title class_">SwitchStatus</span> &#123;  </span><br><span class="line">    <span class="comment">// 枚举的属性字段正例  </span></span><br><span class="line">    DISABLED(<span class="number">0</span>, <span class="string">&quot;禁用&quot;</span>),  </span><br><span class="line">    ENABLED(<span class="number">1</span>, <span class="string">&quot;启用&quot;</span>);  </span><br><span class="line">    <span class="comment">// final 修饰  </span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="type">int</span> value;  </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> String description;  </span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">SwitchStatus</span><span class="params">(<span class="type">int</span> value, String description)</span> &#123;  </span><br><span class="line">        <span class="built_in">this</span>.value = value;  </span><br><span class="line">        <span class="built_in">this</span>.description = description;  </span><br><span class="line">    &#125;  </span><br><span class="line">    <span class="comment">// 没有Setter 方法  </span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getValue</span><span class="params">()</span> &#123;  </span><br><span class="line">        <span class="keyword">return</span> value;  </span><br><span class="line">    &#125;  </span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getDescription</span><span class="params">()</span> &#123;  </span><br><span class="line">        <span class="keyword">return</span> description;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<h4 id="String-split-String-regexp-部分关键字需要转译"><a href="#String-split-String-regexp-部分关键字需要转译" class="headerlink" title="String.split(String regexp) 部分关键字需要转译"></a><code>String.split(String regexp)</code> 部分关键字需要转译</h4><blockquote>
<p>使用字符串String 的split 方法时，传入的分隔字符串是正则表达式，则部分关键字（比如 .<a href></a>| 等）需要转义。</p>
</blockquote>
<p>一个反例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// String.split(String regex) 反例  </span></span><br><span class="line">String[] split = <span class="string">&quot;a.ab.abc&quot;</span>.split(<span class="string">&quot;.&quot;</span>);  </span><br><span class="line">System.out.println(Arrays.toString(split));   <span class="comment">// 结果为[]  </span></span><br><span class="line">String[] split1 = <span class="string">&quot;a|ab|abc&quot;</span>.split(<span class="string">&quot;|&quot;</span>);  </span><br><span class="line">System.out.println(Arrays.toString(split1));  <span class="comment">// 结果为[&quot;a&quot;, &quot;|&quot;, &quot;a&quot;, &quot;b&quot;, &quot;|&quot;, &quot;a&quot;, &quot;b&quot;, &quot;c&quot;] </span></span><br></pre></td></tr></table></figure>
<p>一个正例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// String.split(String regex) 正例  </span></span><br><span class="line"><span class="comment">// . 需要转译  </span></span><br><span class="line">String[] split2 = <span class="string">&quot;a.ab.abc&quot;</span>.split(<span class="string">&quot;\\.&quot;</span>);  </span><br><span class="line">System.out.println(Arrays.toString(split2));  <span class="comment">// 结果为[&quot;a&quot;, &quot;ab&quot;, &quot;abc&quot;]  </span></span><br><span class="line"><span class="comment">// | 需要转译  </span></span><br><span class="line">String[] split3 = <span class="string">&quot;a|ab|abc&quot;</span>.split(<span class="string">&quot;\\|&quot;</span>);  </span><br><span class="line">System.out.println(Arrays.toString(split3));  <span class="comment">// 结果为[&quot;a&quot;, &quot;ab&quot;, &quot;abc&quot;]  </span></span><br></pre></td></tr></table></figure>

    </div>

    
    
    
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/java/" rel="tag"># java</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/09/25/mysql%E5%9F%BA%E7%A1%80%E6%93%8D%E4%BD%9C/" rel="prev" title="mysql基础操作">
      <i class="fa fa-chevron-left"></i> mysql基础操作
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/09/29/lombok%E6%B3%A8%E8%A7%A3%E7%AF%87/" rel="next" title="lombok注解篇">
      lombok注解篇 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#mybatis-%E4%B8%8D%E8%A6%81%E4%B8%BA%E4%BA%86%E5%A4%9A%E4%B8%AA%E6%9F%A5%E8%AF%A2%E6%9D%A1%E4%BB%B6%E8%80%8C%E5%86%99-1-1"><span class="nav-number">1.</span> <span class="nav-text">mybatis 不要为了多个查询条件而写 1&#x3D;1</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%BF%AD%E4%BB%A3-entrySet-%E8%8E%B7%E5%8F%96-Map-%E7%9A%84-key-%E5%92%8C-value"><span class="nav-number">2.</span> <span class="nav-text">迭代 entrySet() 获取 Map 的 key 和 value</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-Collection-isEmpty-%E6%A3%80%E6%B5%8B%E7%A9%BA"><span class="nav-number">3.</span> <span class="nav-text">使用 Collection.isEmpty() 检测空</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%88%9D%E5%A7%8B%E5%8C%96%E9%9B%86%E5%90%88%E6%97%B6%EF%BC%8C%E5%B0%BD%E9%87%8F%E6%8C%87%E5%AE%9A%E5%85%B6%E5%A4%A7%E5%B0%8F"><span class="nav-number">4.</span> <span class="nav-text">初始化集合时，尽量指定其大小</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-StringBuilder-%E6%8B%BC%E6%8E%A5%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="nav-number">4.1.</span> <span class="nav-text">使用 StringBuilder 拼接字符串</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%8B%A5%E9%9C%80%E9%A2%91%E7%B9%81%E8%B0%83%E7%94%A8-Collection-contains-%E6%96%B9%E6%B3%95%E5%88%99%E4%BD%BF%E7%94%A8-Set"><span class="nav-number">5.</span> <span class="nav-text">若需频繁调用 Collection.contains() 方法则使用 Set</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E9%9D%99%E6%80%81%E4%BB%A3%E7%A0%81%E5%9D%97%E5%AE%9E%E7%8E%B0%E8%B5%8B%E5%80%BC%E9%9D%99%E6%80%81%E6%88%90%E5%91%98%E5%8F%98%E9%87%8F"><span class="nav-number">6.</span> <span class="nav-text">使用静态代码块实现赋值静态成员变量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%88%A0%E9%99%A4%E6%9C%AA%E4%BD%BF%E7%94%A8%E7%9A%84%E5%B1%80%E9%83%A8%E5%8F%98%E9%87%8F%E3%80%81%E6%96%B9%E6%B3%95%E5%8F%82%E6%95%B0%E3%80%81%E7%A7%81%E6%9C%89%E6%96%B9%E6%B3%95%E3%80%81%E5%AD%97%E6%AE%B5%E5%92%8C%E5%A4%9A%E4%BD%99%E7%9A%84%E6%8B%AC%E5%8F%B7%E3%80%82"><span class="nav-number">7.</span> <span class="nav-text">删除未使用的局部变量、方法参数、私有方法、字段和多余的括号。</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%B7%A5%E5%85%B7%E7%B1%BB%E4%B8%AD%E5%B1%8F%E8%94%BD%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0"><span class="nav-number">8.</span> <span class="nav-text">工具类中屏蔽构造函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%88%A0%E9%99%A4%E5%A4%9A%E4%BD%99%E7%9A%84%E5%BC%82%E5%B8%B8%E6%8D%95%E8%8E%B7%E5%B9%B6%E6%8A%9B%E5%87%BA"><span class="nav-number">9.</span> <span class="nav-text">删除多余的异常捕获并抛出</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E8%BD%AC%E5%8C%96%E4%BD%BF%E7%94%A8-String-valueOf-value-%E4%BB%A3%E6%9B%BF-quot-quot-value"><span class="nav-number">10.</span> <span class="nav-text">字符串转化使用 String.valueOf(value) 代替 &quot;&quot; + value</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%81%BF%E5%85%8D%E4%BD%BF%E7%94%A8-BigDecimal-double"><span class="nav-number">11.</span> <span class="nav-text">避免使用 BigDecimal(double)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%BF%94%E5%9B%9E%E7%A9%BA%E6%95%B0%E7%BB%84%E5%92%8C%E9%9D%9E-null"><span class="nav-number">12.</span> <span class="nav-text">返回空数组和非 null</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BC%98%E5%85%88%E4%BD%BF%E7%94%A8%E5%B8%B8%E9%87%8F%E6%88%96%E7%A1%AE%E5%AE%9A%E5%80%BC%E8%B0%83%E7%94%A8-equals-%E6%96%B9%E6%B3%95"><span class="nav-number">13.</span> <span class="nav-text">优先使用常量或确定值调用 equals 方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%9E%9A%E4%B8%BE%E7%9A%84%E5%B1%9E%E6%80%A7%E5%AD%97%E6%AE%B5%E5%BF%85%E9%A1%BB%E6%98%AF%E7%A7%81%E6%9C%89%E4%B8%94%E4%B8%8D%E5%8F%AF%E5%8F%98"><span class="nav-number">14.</span> <span class="nav-text">枚举的属性字段必须是私有且不可变</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#String-split-String-regexp-%E9%83%A8%E5%88%86%E5%85%B3%E9%94%AE%E5%AD%97%E9%9C%80%E8%A6%81%E8%BD%AC%E8%AF%91"><span class="nav-number">15.</span> <span class="nav-text">String.split(String regexp) 部分关键字需要转译</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">田园隐士</p>
  <div class="site-description" itemprop="description">talk is cheap, show me the code</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">347</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
        <span class="site-state-item-count">53</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
        <span class="site-state-item-count">115</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">田园隐士</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">587k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">8:53</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  

</body>
</html>
